package com.lant.web.ao.impl;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.lant.enums.ResponseStatusEnum;
import com.lant.exception.ErrorMsgException;
import com.lant.pojo.LantResult;
import com.lant.pojo.LantUser;
import com.lant.utils.HttpUtils;
import com.lant.utils.ObjectUtils;
import com.lant.web.ao.SMSVerifyAO;
import com.lant.web.ao.UserAO;
import com.lant.web.dto.LoginDTO;
import com.lant.web.dto.RegisterDTO;

@FeignClient(value = "server-provider")
@Service("userAO")
public class UserAOImpl implements UserAO {

    private static final Logger logger = LoggerFactory.getLogger(UserAOImpl.class);

    @Autowired
    private SMSVerifyAO smsVerifyAO;

    @Value("${SERVICE_SERVER_HOST}")
    private String SERVICE_SERVER_HOST;

    private static final String SERVICE_EXCEPTION = "服务出现异常，请联系管理员%s";

    @Override
    public LantResult userLogin(LoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
        // step1：判断参数
        if (ObjectUtils.isNull(loginDTO)) {
            throw new ErrorMsgException("参数不能为空");
        }

        // step2：判断用户名
        String userName = loginDTO.getUserName();
        if (ObjectUtils.isNull(userName)) {
            throw new ErrorMsgException("用户名不能为空");
        }

        // step3：判断密码
        String password = loginDTO.getPassword();
        if (ObjectUtils.isNull(password)) {
            throw new ErrorMsgException("密码不能为空");
        }

        // step4：用户登录
        RestTemplate restTemplate = new RestTemplate();
        // step5：封装登录参数
        Map<String, Object> params = new HashMap<>();
        params.put("userName", userName);
        params.put("password", password);
        params.put("request", request);
        params.put("response", response);

        String serviceHost = String.format(SERVICE_SERVER_HOST, "/user/login");
        LantResult result = HttpUtils.post(restTemplate, serviceHost, "", params);
        // step6：查看接口调用是否正常
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, result.getMsg()));
            throw new ErrorMsgException(result.getMsg());
        }

        return result;
    }

    @Override
    public LantResult getUserByToken(String token) {
        // step1：判断参数
        if (ObjectUtils.isNull(token)) {
            throw new ErrorMsgException("参数不能为空");
        }

        // step2：通过token查询redis中用户信息
        RestTemplate restTemplate = new RestTemplate();
        // step3：封装登录参数
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);

        String serviceHost = String.format(SERVICE_SERVER_HOST, "/user/getUserByToken");
        LantResult result = HttpUtils.post(restTemplate, serviceHost, "", params);
        // step4：查看接口调用是否正常
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, result.getMsg()));
            throw new ErrorMsgException(result.getMsg());
        }

        return result;
    }

    @Override
    public LantResult logoffUserByToken(String token) {
        // step1：判断参数
        if (ObjectUtils.isNull(token)) {
            throw new ErrorMsgException("参数不能为空");
        }

        // step2：通过token 安全退出
        RestTemplate restTemplate = new RestTemplate();
        // step3：封装登录参数
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);

        String serviceHost = String.format(SERVICE_SERVER_HOST, "/user/logoff");
        LantResult result = HttpUtils.post(restTemplate, serviceHost, "", params);
        // step4：查看接口调用是否正常
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, result.getMsg()));
            throw new ErrorMsgException(result.getMsg());
        }

        return result;
    }

    @Override
    public LantResult checkData(String content, Integer type) {
        // step1：判断参数
        if (ObjectUtils.isNull(content) || ObjectUtils.isNull(type)) {
            throw new ErrorMsgException("参数不能为空");
        }

        // step2：对用户数据进行校验
        RestTemplate restTemplate = new RestTemplate();
        // step3：封装登录参数
        Map<String, Object> params = new HashMap<>();
        params.put("content", content);
        params.put("type", type);

        String serviceHost = String.format(SERVICE_SERVER_HOST, "/user/checkData");
        LantResult result = HttpUtils.post(restTemplate, serviceHost, "", params);
        // step4：查看接口调用是否正常
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, result.getMsg()));
            throw new ErrorMsgException(result.getMsg());
        }

        return result;
    }

    @Override
    public LantResult createUser(RegisterDTO registerDTO) {
        // step1：判断参数
        if (ObjectUtils.isNull(registerDTO)) {
            throw new ErrorMsgException("参数不能为空");
        }

        if (ObjectUtils.isNull(registerDTO.getUserName())) {
            throw new ErrorMsgException("用户名不能为空");
        }

        // 检测短信验证码
        LantResult checkSMSResult = smsVerifyAO.checkSMSVerify(registerDTO.getVercode(), registerDTO.getMobile());

        if (checkSMSResult.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, checkSMSResult.getMsg()));
            throw new ErrorMsgException(checkSMSResult.getMsg());
        }

        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            throw new ErrorMsgException("两次输入密码不一致");
        }

        // step2：封装注册数据
        LantUser user = new LantUser();
        user.setUserName(registerDTO.getUserName());
        user.setPassword(registerDTO.getPassword());
        user.setMobile(registerDTO.getMobile());

        // step3：用户注册
        RestTemplate restTemplate = new RestTemplate();
        // // step4：封装注册参数
        Map<String, Object> params = new HashMap<>();
        params.put("userJson", LantResult.formatPojoToString(user));

        String serviceHost = String.format(SERVICE_SERVER_HOST, "/user/createUser");
        LantResult result = HttpUtils.post(restTemplate, serviceHost, "", params);
        // step4：查看接口调用是否正常
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format(SERVICE_EXCEPTION, result.getMsg()));
            throw new ErrorMsgException(result.getMsg());
        }

        return result;
    }

}
